package com.zhengxyou.jetpackdemo.lifecycle_liveData_viewModel.view_model;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.lang.ref.WeakReference;

import androidx.lifecycle.LiveData;

public class MyLiveData extends LiveData<Integer> {
    final String TAG = "MyLiveData";
    private static MyLiveData mInstance;
    private WeakReference<Context> weakReference;

    private MyLiveData(Context context) {
        weakReference = new WeakReference<>(context);
    }

    public static MyLiveData getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MyLiveData(context);
        }
        return mInstance;
    }

    @Override
    protected void onActive() {
        super.onActive();
        registerReceiver();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        weakReference.get().registerReceiver(mReceiver, intentFilter);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        unRegisterReceiver();
    }

    private void unRegisterReceiver() {
        weakReference.get().unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "action" + action);
            if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
                int wifiRssi = intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, -200);
                int wifiLevel = WifiManager.calculateSignalLevel(wifiRssi, 4);
                mInstance.setValue(wifiLevel);
            }
        }
    };
}
